package handlers

import (
	"encoding/json"
	"game-master/cache"
	"game-master/models"
	"game-master/pkg"
	"github.com/gin-gonic/gin"
	"strconv"
	"time"
)

func Login(c *gin.Context) {
	username := c.Query("username")
	password := c.Query("password")

	redis_key := "game_login" + username
	errLogin, _ := cache.Rdb.Get(cache.Ctx, redis_key).Int()
	if errLogin >= 3 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "错误三次,禁止登录",
		})
		return
	}
	var login models.User
	err := models.DB.Where("username = ?", username).First(&login).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "用户不存在",
		})
		return
	}

	if pkg.Md5str(password) != login.Password {
		cache.Rdb.Incr(cache.Ctx, redis_key)
		if errLogin == 2 {
			cache.Rdb.Set(cache.Ctx, redis_key, 3, time.Hour*2)
			c.JSON(200, gin.H{
				"code": 500,
				"msg":  "错误三次,禁封2小时",
			})
			return
		}
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "密码错误",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "登录成功",
	})
	return

}
func List(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "3"))
	offset := (page - 1) * size

	var list []models.Game

	redis_key := "game_list" + strconv.Itoa(page)
	cacheDate, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheDate == "" {
		models.DB.Offset(offset).Limit(size).Find(&list)
		jsonData, _ := json.Marshal(list)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheDate), &list)
	}
	var count int64
	err := models.DB.Model(&models.Game{}).Count(&count).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "查询失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "查询成功",
		"count": count,
		"list":  list,
	})
	return

}
func Details(c *gin.Context) {
	id := c.Query("id")
	var detail models.Game
	models.DB.Where("id = ?", id).First(&detail)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": detail,
	})
}
